package com.ecoolex.chinadutyfree.retailer.core.manager;

import java.sql.Date;
import java.time.Instant;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ecoolex.chinadutyfree.retailer.core.dao.DirectMailGoodsDummyDAO;
import com.ecoolex.chinadutyfree.retailer.entity.DirectMailGoods;
import com.ecoolex.chinadutyfree.retailer.entity.DirectMailGoodsDummy;
import com.ecoolex.chinadutyfree.retailer.entity.DirectMailGoodsDummy.Column;
import com.ecoolex.framework.common.enums.ResultCode;
import com.ecoolex.framework.common.util.BizAssert;
import com.ecoolex.framework.common.util.Check;

@Service
public class DirectMailGoodsDummyManager {

	@Autowired
	private DirectMailGoodsDummyDAO dao;

	public void create(DirectMailGoods goods, String createUser) {
		DirectMailGoodsDummy record = new DirectMailGoodsDummy();
		record.setDirectMailGoodsId(goods.getDirectMailGoodsId());
		record.setInitialValueSales(0);
		record.setSalesIncremental(0);
		record.setDeleted(DirectMailGoodsDummy.NOT_DELETED);
		record.setCreateUser(createUser);
		record.setCreateTime(Date.from(Instant.now()));
		record.setUpdateUser(createUser);
		record.setUpdateTime(Date.from(Instant.now()));
		dao.insert(record);
	}

	private void verify(DirectMailGoodsDummy record) {
		BizAssert.isTrue(Check.notNullAndGteZero(record.getInitialValueSales()),
			ResultCode.VERIFY.build(10),
			"初始化销量为空或者小于0");
		BizAssert.isTrue(Check.notNullAndGteZero(record.getSalesIncremental()),
			ResultCode.VERIFY.build(10),
			"销售增量为空或者小于0");
	}

	public DirectMailGoodsDummy update(DirectMailGoodsDummy record, String updateUser) {
		verify(record);

		record.setUpdateUser(updateUser);
		record.setUpdateTime(Date.from(Instant.now()));

		dao.updateByPrimaryKeySelective(record, Column.excludes(Column.deleted, Column.createUser, Column.createTime));
		return record;
	}

	public DirectMailGoodsDummy getByDirectMailGoodsId(Integer directMailGoodsId) {
		return dao.selectByPrimaryKeyWithLogicalDelete(directMailGoodsId, DirectMailGoodsDummy.NOT_DELETED);
	}

	public void deleteByDirectMailGoodsId(Integer directMailGoodsId, String updateUser) {
		DirectMailGoodsDummy record = getByDirectMailGoodsId(directMailGoodsId);
		record.setDeleted(DirectMailGoodsDummy.IS_DELETED);
		record.setUpdateUser(updateUser);
		record.setUpdateTime(Date.from(Instant.now()));
		dao.updateByPrimaryKeySelective(record, Column.deleted, Column.updateUser, Column.updateTime);
	}
}